package game;

import util.*;
import java.sql.*;

public class GameDispatcher{
	private DBManager dbManager;
	private String table;
	
	public GameDispatcher(DBManager dbManager, String table){
		this.dbManager = dbManager;
		this.table = table;
	}
	
	private Statement getStatement(){
		try{
			Connection connection = dbManager.getConnection();
			return connection.createStatement();
		}catch(SQLException e){
			return null;
		}
	}
	
	
	
	public boolean saveGame(SingleGame game){ 
		Statement statement = getStatement();
		if(statement==null)
			return false;
		String query = "INSERT INTO "+table+" (userID, startTime, endTime, results, difficulty) values ("+
			game.getUserID()+", "+
			"SUBDATE(NOW(), INTERVAL "+(game.getEndTime().getTime()-game.getStartTime().getTime())/1000+" SECOND), "+   
			" NOW()"+", "+
			game.getResult()+", "+
			game.getDifficulty()+");";
		try{
			statement.executeUpdate(query);
		}catch(SQLException e){
			System.out.println(e);
			return false;
		}
		return true;
	}
	
	public static void main(String arg[]){
		DBManager dbManager = new DBManager("anagram", "root", "root");
		GameDispatcher d = new GameDispatcher(dbManager, "games");
		SingleGame game = new SingleGame(1, "qwerty");
		game.addAnswer("qwerty");
		d.saveGame(game);
	}
}
